package com.kingsoft.miot.bridge.service.impl.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.kingsoft.miot.bridge.config.RedisConfig;
import com.kingsoft.miot.bridge.controller.resp.HotelInfoRoleResp;
import com.kingsoft.miot.bridge.dao.HotelInfoDao;
import com.kingsoft.miot.bridge.dao.PageBean;
import com.kingsoft.miot.bridge.dao.manager.ManagerGroupRecordDao;
import com.kingsoft.miot.bridge.dao.manager.ManagerInfoDao;
import com.kingsoft.miot.bridge.exception.CommonException;
import com.kingsoft.miot.bridge.pojo.hotel.HotelInfo;
import com.kingsoft.miot.bridge.pojo.manager.GroupInfo;
import com.kingsoft.miot.bridge.pojo.manager.ManagerGroupRecord;
import com.kingsoft.miot.bridge.pojo.manager.ManagerInfo;
import com.kingsoft.miot.bridge.service.manager.GroupInfoService;
import com.kingsoft.miot.bridge.service.manager.ManagerService;

/**
 * 管理员信息服务
 * 
 * @author HUJIANQING
 *
 */
@Service
@CacheConfig(cacheNames = { RedisConfig.MANAGER_CACHE })
public class ManagerServiceImpl implements ManagerService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ManagerServiceImpl.class);

	// 管理者 DAO
	@Autowired
	private ManagerInfoDao managerInfoDao;
	// 管理者 权限组
	@Autowired
	private ManagerGroupRecordDao managerGroupRecordDao;
	// hotel
	@Autowired
	private HotelInfoDao hotelInfoDao;
	// 角色服务
	@Autowired
	private GroupInfoService groupInfoService;

	@Cacheable(key = "#id")
	public String getTest(String id) {
//		Object leftPop = redis.opsForList().
//		if(leftPop == null) {
//		Object data = redisUtils.hget(RedisConfig.MANAGER_CACHE, "melody");
//		if (data != null) {
//			return data.toString();
//		}
		return new String(id + new Date().getTime());
//		}
//		return new String(leftPop.toString());
//		return leftPop.toString();
	}

	@CachePut(key = "#id")
	public String addTest(String id) {
		String x = id + new Date().getTime();
//		boolean isSuccess = redisUtils.hset(RedisConfig.MANAGER_CACHE, "melody", x, 100);
//		redis.opsForList().leftPush(id,x );
		return x;
	}

	/**
	 * 创建管理者并添加权限
	 * 
	 * @param hotelid
	 * @param managerInfo
	 */
	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public void addManager(@Param("managerInfo") ManagerInfo managerInfo) {
		// 1.查询是否存在hotel
		try {
			HotelInfo hotelInfo = hotelInfoDao.getById(managerInfo.getHotel_info_id());
			if (hotelInfo == null) {
				LOGGER.error("查询酒店为空，不能添加管理者。");
				return;
			}
			managerInfoDao.addManager(managerInfo);
		} catch (Exception e) {
			LOGGER.error("创建管理员失败。");
			return;
		}
	}

	/**
	 * 通过ID 删除管理员 成功返: 1 失败: -1
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int deleteManagerById(int manager_info_id) {
		try {
			// 1, 删除 manager
			ManagerInfo managerInfo = getManagerInfoById(manager_info_id);
			if (managerInfo == null) {
				return -1;
			}
			int flag = managerInfoDao.deleteById(manager_info_id);
			if (flag == 0) {
				return -1;
			}
			// 2.删除manager - group 记录
			List<ManagerGroupRecord> managerGroupRecordList = managerGroupRecordDao
					.selectListByManagerId(manager_info_id);
			if (managerGroupRecordList != null && managerGroupRecordList.size() > 0) {
				for (ManagerGroupRecord managerGroupRecord : managerGroupRecordList) {
					managerGroupRecordDao.deleteById(managerGroupRecord.getManager_group_record_id());
				}
			}
			// 3. 从酒店中删除所有管理员
			String email = managerInfo.getManager_info_email();
			// 获取包含该email的所有 酒店 并将酒店中管理员删除
			List<HotelInfo> hotelInfoList = hotelInfoDao.getListByManagerEmail(email);
			for (int i = 0; i < hotelInfoList.size(); i++) {
				HotelInfo hotelInfo = hotelInfoList.get(i);
				deleteEmail(hotelInfo, email);
			}
			// 删除该管理员后 批量更新该酒店信息
			hotelInfoDao.updateList(hotelInfoList);
			return 1;
		} catch (Exception e) {
			LOGGER.error("删除管理员失败。");
			throw new RuntimeException(e);
		}

	}

	/**
	 * 删除email
	 * 
	 * @param hotelInfo
	 * @param email
	 */
	private void deleteEmail(HotelInfo hotelInfo, String email) {
		try {
			String emailStr = hotelInfo.getHotel_info_managers();
			List<String> emailList = JSON.parseObject(emailStr, List.class);
			if (emailList != null && emailList.size() > 0) {
				emailList.remove(email);
			}
			JSONObject jsonObject = new JSONObject();
			String jsonString = jsonObject.toJSONString(emailList);
			hotelInfo.setHotel_info_managers(jsonString);
		} catch (Exception e) {
			throw new CommonException(e);
		}
	}

	/**
	 * 通过Id查询manager
	 */
	@Transactional
	@Override
	public ManagerInfo getManagerInfoById(int managerId) {
		try {
			ManagerInfo managerInfo = managerInfoDao.getById(managerId);
			return managerInfo;
		} catch (Exception e) {
			LOGGER.error("查询manager失败");
		}
		return null;
	}

	/**
	 * 查询所有的ManagerIno
	 */
	@Override
	public List<ManagerInfo> findAll() {
		try {
			List<ManagerInfo> managerInfolList = managerInfoDao.findAll();
			return managerInfolList;
		} catch (Exception e) {
			LOGGER.error("查询manager 列表 失败。");
		}
		return null;
	}

	/**
	 * 通过email获取管理者
	 */
	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public ManagerInfo getByEmail(String email) {
		ManagerInfo managerInfo = null;
		try {
			managerInfo = managerInfoDao.getByEmail(email);
		} catch (Exception e) {
			throw new CommonException(e);
		}
		return managerInfo;
	}

	/**
	 * 更新manager 信息 这里涉及的 IAM
	 */
	@Override
	public int updateManager(ManagerInfo manager_info) {
		try {
			managerInfoDao.update(manager_info);
			return 1;
		} catch (Exception e) {
			throw new CommonException(e);
		}
	}

	/**
	 * 通过多个email删除管理员 并删除其权限
	 */
	@Override
	public int deleteManagerByEmailList(List<String> emailList) {
		try {
			for (int i = 0; i < emailList.size(); i++) {
				if (StringUtils.isNotBlank(emailList.get(i))) {
					ManagerInfo tmpManager = managerInfoDao.getByEmail(emailList.get(i));
					if (tmpManager != null) {
						// 删除管理员 并删除其权限
						deleteManagerById(tmpManager.getManager_info_id());
					}
				}
			}
			return 1;
		} catch (Exception e) {
			throw new CommonException(e);
		}
	}

	/**
	 * 通过用户名和密码查询用户信息
	 */
	@Override
	public ManagerInfo getByNameAndPwd(int manager_info_id, String passwdord) {
		try {
			Map<String, Object> argMap = new HashMap<>();
			argMap.put("manager_info_id", manager_info_id);
			argMap.put("manager_info_password", passwdord);
			ManagerInfo managerInfo = managerInfoDao.getByIdAndPwd(argMap);
			return managerInfo;
		} catch (Exception e) {
			throw new CommonException(e);
		}
	}

	/**
	 * 通过酒店ID返回所有的信息
	 */
	@Override
	public HotelInfoRoleResp getByHotelInfoId(int currentPage, int pageSize, int hotel_info_id) {
		try {
			List<ManagerInfo> managerInfoList = managerInfoDao.getByHotelInfoId(hotel_info_id);

			PageHelper.startPage(currentPage, pageSize);
			HotelInfoRoleResp result = new HotelInfoRoleResp();
			// 暂时查询总记录数
			int countNums = managerInfoList.size(); // 总记录数
			PageBean<ManagerInfo> pageData = new PageBean<>(currentPage, pageSize, countNums);
			pageData.setItems(managerInfoList);
			result.setCurrent_page(currentPage);
			result.setSize(pageSize);
			result.setTotal_count(countNums);
			result.setTotal_pages(pageData.getTotalPage());
			// 起始也
			int start = (currentPage - 1) * pageSize >= managerInfoList.size()
					? (managerInfoList.size() / pageSize) * pageSize
					: (currentPage - 1) * pageSize;
			// 最终页
			int end = currentPage * pageSize >= managerInfoList.size() ? managerInfoList.size()
					: currentPage * pageSize;
			List<ManagerInfo> subList = managerInfoList.subList(start, end);
			List<Map<String, Object>> dataList = new ArrayList<>();
			// 设置返回数据 需要改进 bean utils
			for (ManagerInfo item : subList) {
				Map<String, Object> dataMap = new HashMap<>();
				dataMap.put("manager", item.getManager_info_email());
				GroupInfo groupInfo = groupInfoService.getById(item.getGroup_info_id());
				dataMap.put("permission", groupInfo.getGroup_info_name());
				dataMap.put("mobile", item.getManager_info_phone());
				dataMap.put("create_time", item.getManager_info_create().getTime());
				dataList.add(dataMap);
			}
			result.setList(dataList);
			return result;
		} catch (Exception e) {
			throw new CommonException(e);
		}
	}

}
